package java

import (
	"math"
	"unsafe"

	"gitee.com/microwww/jvm-go/jvm/class"
)

type Slots []Slot

func NewLocalVar(max uint16) Slots {
	if max > 0 {
		return make([]Slot, max)
	}
	return nil
}

func (v Slots) SetInt(index uint, val int32) {
	v[index].Num = val
}

func (v Slots) GetInt(index uint) int32 {
	return v[index].Num
}

func (v Slots) SetRef(index uint, obj *class.Object) {
	pt := unsafe.Pointer(obj)
	v[index] = Slot{
		Num: int32(uintptr(pt)),
		Ref: obj,
	}
}

func (v Slots) GetRef(index uint) *class.Object {
	return v[index].Ref
}

func (v Slots) SetSlot(index uint, slot Slot) {
	v[index] = slot
}

func (v Slots) GetSlot(index uint) Slot {
	return v[index]
}

func (v Slots) SetLong(index uint, val int64) {
	low, height := long2int(val)
	v[index].Num = low
	v[index+1].Num = height
}

func (v Slots) GetLong(index uint) int64 {
	return int2long(v[index].Num, v[index+1].Num)
}

func (v Slots) SetFloat(index uint, val float32) {
	f32 := math.Float32bits(val)
	v[index] = Slot{
		Num: int32(f32),
	}
}

func (v Slots) GetFloat(index uint) float32 {
	vi := v[index].Num
	return math.Float32frombits(uint32(vi))
}

func (v Slots) SetDouble(index uint, val float64) {
	f := math.Float64bits(val)
	v.SetLong(index, int64(f))
}

func (v Slots) GetDouble(index uint) float64 {
	f := v.GetLong(index)
	return math.Float64frombits(uint64(f))
}
